package anything.jdom;
/*
 * LineData.java
 *
 */
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.util.Hashtable;
/**
 *
 * @author  Solariise
 */
public class TerminalXML {
  static Document document;
  public Hashtable conf_hash = null;
  
  /** Creates a new instance of LineData */
  public TerminalXML(String filename) {
    conf_hash = new Hashtable();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //factory.setValidating(true);
    //factory.setNamespaceAware(true);
    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse( new File(filename) );
      operatingInput();
      
    } catch (SAXException sxe) {
      // Error generated during parsing)
      Exception  x = sxe;
      if (sxe.getException() != null)
        x = sxe.getException();
      x.printStackTrace();
      
    } catch (ParserConfigurationException pce) {
      // Parser with specified options can't be built
      pce.printStackTrace();
      
    } catch (IOException ioe) {
      // I/O error
      ioe.printStackTrace();
    }
  }
  private void operatingInput(){
    Node root = document.getDocumentElement();
    //output("Root node = " + root.getNodeName());
    
    NodeList childNodes = root.getChildNodes();
    Node currentNode;
    
    for(int i = 0; i < childNodes.getLength(); i++) {
      currentNode = childNodes.item(i);
      //output("Node name is = " + currentNode.getNodeName());
      processNode(currentNode);
    }
    //output(getValue("dbskin", "driver"));
  }
  
  private void processInnerNode(Node n, String parentNodeName) {
    if(n.getFirstChild()!=null){
      conf_hash.put(parentNodeName + ":" + n.getNodeName(), n.getFirstChild().getNodeValue() );
      processInnerNode(n.getNextSibling(), parentNodeName);
    }
  }
  
  
  private void processNode(Node n) {
    NodeList nl;
    NamedNodeMap nmp;
    Node att_node;
    
    if(n.hasAttributes()) {
      nmp = n.getAttributes();
      for(int i = 0; i < nmp.getLength() ; i++) {
        att_node = nmp.item(i);
        nl = n.getChildNodes();
        for(int j = 0 ; j < nl.getLength(); j++) {
          n = nl.item(j);
          processInnerNode(n, att_node.getNodeValue());
        }
      } // end for i
    } else { // end main if
      String nodename = n.getNodeName();
      nl = n.getChildNodes();
      for(int i = 0; i < nl.getLength(); i++) {
        n = nl.item(i);
        processInnerNode(n, nodename);
      }
    } // end else
  }
  
  public String getValue(String serverName, String domain) {
    String out = conf_hash.get(serverName + ":" + domain).toString();
    return out;
  }
  
  private void output(String input) {
    System.out.println(input);
  }
  
  public static void main(String argv[]) {
    TerminalXML txml = new TerminalXML("res/test/jdom/touchscreen_conf.xml");
    System.out.println(txml.getValue("dbskin", "ip"));
  }
}
